package com.example.hospitaltraining.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import com.example.hospitaltraining.exception.GlobalExceptionHandler;
import com.example.hospitaltraining.pojo.UserMsg;
import com.example.hospitaltraining.service.UserMsgService;
import com.example.hospitaltraining.utils.SM4DecryptionExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMsgService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("拦截成功"+token);

        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }else
        {
            //判断有没有加上不用权限也可以访问的注解
            HandlerMethod h = (HandlerMethod) handler;
            AuthAccess methodAnnotation = h.getMethodAnnotation(AuthAccess.class);
            System.out.println(methodAnnotation);
            if(methodAnnotation != null){
                return true;
            }

        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new GlobalExceptionHandler.ServiceException("401", "无token，请重新登录");
        }
        String userId;
        try {
            System.out.println("\n\n"+JWT.decode(token).getAudience().get(0));
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new GlobalExceptionHandler.ServiceException("401", "token验证失败，请重新登录");
        }

        // 根据token中的userid查询数据库
        UserMsg user = userService.getById(userId);
        if (user == null) {
            throw new GlobalExceptionHandler.ServiceException("401", "用户不存在，请重新登录");
        }
        // 用户密码加签验证 token
        String key  = "0123456789abcdeffedcba9876543210";
        user.setIdNumber(SM4DecryptionExample.encrypt(key,user.getIdNumber()));
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getIdNumber())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            System.out.println(e);
            throw new GlobalExceptionHandler.ServiceException("401", "token验证失败，请重新登录");
        }
        return true;
    }

}
